import time
from threading import Thread, Lock

num = 0


def func(lock):
    global num
    # # 不合理使用：被锁代码的粒度太小，导致程序运行中，因为频繁的加锁与解锁浪费了大量CPU资源
    # for i in range(500000):
    #     with lock:
    #         num += 1

    # 合理使用：
    with lock:
        for i in range(500000):
            num += 1


if __name__ == '__main__':
    t1 = time.time()
    thread_list = []
    lock = Lock()
    for i in range(10):
        t = Thread(target=func, args=(lock,))
        t.start()
        thread_list.append(t)

    for t in thread_list:
        t.join()
    t2 = time.time()
    print(f"num={num}, {t2 - t1}")  # num=2000000
